package nbn.android.myyoutubeclient;

import java.util.ArrayList;

import nbn.android.myyoutubeclient.adapter.PlaylistAdapter;
import nbn.android.myyoutubeclient.object.PlaylistObject;
import nbn.android.myyoutubeclient.parse.Parser;
import nbn.android.myyoutubeclient.parse.ParserPlaylist;
import nbn.android.myyoutubeclient.util.CMD;
import nbn.android.myyoutubeclient.util.TagName;
import nbn.android.myyoutubeclient.view.BounceProgressBar;
import nbn.android.myyoutubeclient.view.CustomActionbar;

import org.w3c.dom.NodeList;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends ActionBarActivity {
	GridView gridViewPlaylist;
	ArrayList<PlaylistObject> playlistObjects;
	PlaylistAdapter adapter;
	BounceProgressBar progressBar;
	int w, h;
	public static android.widget.RelativeLayout.LayoutParams playlist_params;

	private InterstitialAd mInterstitialAd;
	String LOG_TAG = "Admob";
	public CustomActionbar myActionBar;
	private SwipeRefreshLayout mSwipeLayout;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		myActionBar = new CustomActionbar(MainActivity.this, null);
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setIcon(android.R.drawable.ic_popup_sync);
		myActionBar.setTitle("Phim trực tuyến");
		actionBar.setCustomView(myActionBar);

		
		DisplayMetrics metrics = getResources().getDisplayMetrics();
		w = (int) metrics.widthPixels;
		h = (int) metrics.heightPixels;
		int w = (int) (this.w * 0.9 / 2);
		int h = (int) (w * 0.6);
		playlist_params = new android.widget.RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.MATCH_PARENT, h);

		playlistObjects = new ArrayList<PlaylistObject>();
		adapter = new PlaylistAdapter(MainActivity.this, playlistObjects);
		gridViewPlaylist = (GridView) findViewById(R.id.gridViewPlaylist);
		progressBar = (BounceProgressBar) findViewById(R.id.progressBarPlaylist_main);
		gridViewPlaylist.setEmptyView(progressBar);
		gridViewPlaylist.setAdapter(adapter);
		new LoadPlaylistsAsync().execute(CMD.GDATA_USER_PLAYLIST);
		gridViewPlaylist.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent2 = new Intent(getApplicationContext(), PlaylistVideoActivity.class);
				intent2.putExtra(TagName.KEY, playlistObjects.get(position));
				startActivity(intent2);
			}
		});
		initAd();
		mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
		mSwipeLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				new LoadPlaylistsAsync().execute("");
			}
		});
		mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
	}

	class LoadPlaylistsAsync extends AsyncTask<String, PlaylistObject, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			String url = params[0];
			Parser parser = new Parser();
			NodeList movieContentLst = parser.getResponceNodeList(url);
			if (movieContentLst != null) {
				for (int i = 0; i < movieContentLst.getLength(); i++) {
					publishProgress(ParserPlaylist.getResult(movieContentLst, i));
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(PlaylistObject... values) {
			super.onProgressUpdate(values);
			addItem(values);
			adapter.notifyDataSetChanged();
		}

		public void addItem(PlaylistObject... items) {
			for (PlaylistObject item : items) {
				playlistObjects.add(item);
			}
		}

		@Override
		protected void onPostExecute(Void result) {
			if (mSwipeLayout.isRefreshing())
				mSwipeLayout.setRefreshing(false);
			super.onPostExecute(result);
		}
	}


	@Override
	protected void onResume() {
		super.onResume();
		AdRequest adRequest = new AdRequest.Builder().build();
		mInterstitialAd.loadAd(adRequest);
	}

	private void initAd() {
		mInterstitialAd = new InterstitialAd(MainActivity.this);
		mInterstitialAd.setAdUnitId(getResources().getString(R.string.admob_id_full));
		mInterstitialAd.setAdListener(new AdListener() {
			@Override
			public void onAdClosed() {
				Log.d(LOG_TAG, "onAdClosed");
				// PreferenceUtils.putString(VideoPlayActivity.this,
				// TagName.KeyPreference_user, );
				finish();
			}
			@Override
			public void onAdFailedToLoad(int error) {
				String message = "onAdFailedToLoad: " + getErrorReason(error);
				Log.d(LOG_TAG, message);
			}
			@Override
			public void onAdLeftApplication() {
				Log.d(LOG_TAG, "onAdLeftApplication");
			}
			@Override
			public void onAdOpened() {
				Log.d(LOG_TAG, "onAdOpened");
			}
			@Override
			public void onAdLoaded() {
				Log.d(LOG_TAG, "onAdLoaded");
			}
		});
	}

	private String getErrorReason(int errorCode) {
		String errorReason = "";
		switch (errorCode) {
		case AdRequest.ERROR_CODE_INTERNAL_ERROR:
			errorReason = "Internal error";
			break;
		case AdRequest.ERROR_CODE_INVALID_REQUEST:
			errorReason = "Invalid request";
			break;
		case AdRequest.ERROR_CODE_NETWORK_ERROR:
			errorReason = "Network Error";
			break;
		case AdRequest.ERROR_CODE_NO_FILL:
			errorReason = "No fill";
			break;
		}
		return errorReason;
	}

	private void displayAd() {
		if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
			mInterstitialAd.show();
		} else {
			Log.e("Admob", "InterstitialAd: Ad did not load");
			finish();
		}
	}

	@Override
	public void onBackPressed() {
		displayAd();
	};
}